package com.contest.interceptor;

import com.contest.constant.CommonsConstant;
import com.contest.entity.MerchantInfo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpSession session = req.getSession();
        // 获得用户请求的URI
        String path = req.getRequestURI();
        // 从session取得已经证的凭证 我这里的demo用的是password来作为登录凭证
        MerchantInfo token = (MerchantInfo) session.getAttribute(CommonsConstant.LOGIN_SESSION);
        // login.jsp页面无需过滤(根据自己项目的要求来)

        //也可以path.contains("login.jsp")  反正怎么精确怎么来就不多说了
        if (path.indexOf("/login") > -1) {//注意：登录页面千万不能过滤  不然过滤器就。。。。。自行调试不要偷懒！这样记忆深刻
            filterChain.doFilter(req, resp);
            return;
        } else {//如果不是login.jsp进行过滤
            if (token == null || "".equals(token)) {
                // 跳转到登陆页面
                resp.sendRedirect("/login.jsp");
            } else {
                // 已经登陆,继续此次请求
                filterChain.doFilter(req, resp);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
